# -*- coding: utf-8 -*-
"""
Created on Wed Nov 08 15:15:27 2017

@author: za-xuzhaoye
"""

import csv
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller
import statsmodels.api as sm


with open('D:\FOF_strategy\A&H_ETF_data\ClosePrice.csv','rb') as csvfile:
    reader=csv.DictReader(csvfile)
    H_ETF = [row['H_ETF'] for row in reader]  
    float_H_ETF=[float(x) for x in H_ETF]
 

with open('D:\FOF_strategy\A&H_ETF_data\ClosePrice.csv','rb') as csvfile:
    reader=csv.DictReader(csvfile)
    SZETF = [row['50ETF'] for row in reader]
    float_SZETF=[float(x) for x in SZETF]
    
    print  "CORRELATION BETWEEN SZETF AND H_ETF IS "+str(np.corrcoef(float_SZETF,float_H_ETF)[0,1])
    plt.plot(float_H_ETF)
    plt.plot(float_SZETF)
    premium = np.array(float_SZETF)-np.array(float_H_ETF)
    plt.plot(premium)
    plt.xlabel('time')
    plt.ylabel('price')
    plt.legend(['HETF','50ETF','premium'])
    
    adftest=adfuller(premium)
    result=pd.Series(adftest[0:4],index=['test statistic','p-value','lags used','number of observations used'])
    for key, value in adftest[4].items():
        result['Critical Value(%s)'%key]=value
    print result
 
    
    x=np.asarray(float_H_ETF)
    y=np.asarray(float_SZETF)
    X= sm.add_constant(x)
    result=(sm.OLS(y,X)).fit()
    print(result.summary())
    
    
    diff=y-2.0463*x
    diff=pd.Series(diff,index=range(len(x)))
    mean=np.mean(diff)
    std= np.std(diff)
    print(std)
    up=mean+std
    down=mean-std

    mean_line=pd.Series(mean,index=range(len(x)))
    up_line=pd.Series(up,index=range(len(x)))
    down_line=pd.Series(down, index=range(len(x)))
    set=pd.concat([diff,mean_line,up_line,down_line],axis=1)
    set.plot(figsize=(14,7))
    plt.legend(['diff','mean','up','down'])
    print up, down
    